// 店铺数据
import {getShopSellerReq, getGoodsListReq, getShopRateReq} from '@/api/shop'
const state = {
  shopData: {},
  goodsList: [],
  rateList: [],
}

const getters = {
  navs(state) {
    return state.goodsList.map(v => v.name)
  },
  // 筛选
  goodRateList(state) {
    return state.rateList.filter(v => {
      return v.score > 3
    })
  },
  badRateList(state) {
    return state.rateList.filter(v => {
      return v.score <= 3
    })
  },
  // 筛选食品列表
  filterFoodList(state) {
    let temp = []
    state.goodsList.forEach(good => {
      good.foods.forEach(food => {
        if (food.count > 0) {
          temp.push(food)
        }
      })
    })
    return temp
  },

  // 总数量
  filterTotalCount(state, getters) {
    return getters.filterFoodList.reduce((total, cur) => {
      return total + cur.count
    }, 0)
  },
  // 总价格
  filterTotalPrice(state, getters) {
    return getters.filterFoodList.reduce((total, cur) => {
      return total + cur.count * cur.price
    }, 0)
  },
}

const mutations = {
  SET_SHOPINFO(state, data) {
    state.shopData = data
  },
  SET_GOODSLIST(state, data) {
    state.goodsList = data
  },
  SET_SHOPRATE(state, data) {
    state.rateList = data
  },
}

const actions = {
  // 店铺数据
  A_getShopInfo({commit}) {
    return new Promise(async (resolve, reject) => {
      let res = await getShopSellerReq()
      let {data} = res.data
      commit('SET_SHOPINFO', data)
    })
  },
  // 商品列表
  A_getGoodsList({commit}) {
    return new Promise(async (resolve, reject) => {
      let res = await getGoodsListReq()
      let {code, data} = res.data
      if (code === 0) {
        data.forEach(v => {
          v.foods.forEach(subV => {
            //给每个食品新增一个count字段
            subV.count = 0
          })
        })
        commit('SET_GOODSLIST', data)
        resolve()
      }
    })
  },
  // 评价
  A_getShopRate({commit}) {
    return new Promise(async (resolve, reject) => {
      let res = await getShopRateReq()
      let {errno, data} = res.data
      if (errno === 0) {
        commit('SET_SHOPRATE', data)
        resolve()
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
